//
//  SleepViewController.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/27.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

import CoreMotion

class SleepViewController: SleepBaseViewController {
    @IBOutlet weak var musicName: UILabel!
    @IBOutlet weak var coverImage: UIImageView! {
        didSet {
            coverImage.layer.cornerRadius = coverImage.bounds.width / UIScreen.main.scale
            coverImage.image = UIImage(named: "pic_bg_login")
            coverImage.layer.masksToBounds = true
            coverImage.layer.borderColor = UIColor("#052726").cgColor
            coverImage.layer.borderWidth = 6
        }
    }

    let sleepTracker = SleepTracker()
    var record = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpSleepTracker()
    }

    @IBAction func playPrevious(_ sender: UIButton) {
    }

    @IBAction func playNext(_ sender: UIButton) {
    }

    private func setUpSleepTracker() {
        sleepTracker.actionEachInterval = { [weak self] vibration in
            switch vibration {
            case 0..<15.0:
                self?.record += "a"
            case 15.0..<90.0:
                self?.record += "b"
            case 90.0...:
                self?.record += "c"
            default:
                guard let `self` = self else { return }
                EHLogger.error(in: self, msg: "vibration less than 0.")
            }
        }
        sleepTracker.track()
    }
}

class SleepTracker {
    private var motionManager: CMMotionManager!
    private let queue = OperationQueue()
    private var timer: Timer!

    // 默认为5分钟
    var interval: TimeInterval = 5 * 60 {
        didSet {
            if timer != nil {
                EHLogger.error(in: self, msg: "should set property before tracking.")
            }
        }
    }

    // 参数为震动值
    var actionEachInterval: (Double) -> Void = { _ in } {
        didSet {
            if timer != nil {
                EHLogger.error(in: self, msg: "should set property before tracking.")
            }
        }
    }

    // 每5分钟的起始参考值X
    private var baseX: Double = 0

    // 每5分钟的起始参考值Y
    private var baseY: Double = 0

    // 5分钟内偏移量X
    private var offsetX: Double = 0

    // 5分钟内偏移量Y
    private var offsetY: Double = 0

    func track() {
        setUpMotionManager()
        setUpTimer()
    }

    private func restore() {
        baseX = 0
        baseY = 0
        offsetX = 0
        offsetY = 0
    }

    @objc func loop() {
        debugPrint("5minutes:", self.offsetX, self.offsetY)
        // 震动值为offsetX，offsetY的值各乘以100，再求和
        let vibration = self.offsetX * 100 + self.offsetY * 100
        self.actionEachInterval(vibration)
        self.restore()
    }

    private func setUpTimer() {
        // 每个周期采集一次, 还原到出事状态
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: { [weak self] (_) in
            guard let `self` = self else { return }
            debugPrint("5minutes:", self.offsetX, self.offsetY)
            // 震动值为offsetX，offsetY的值各乘以100，再求和
            let vibration = self.offsetX * 100 + self.offsetY * 100
            self.actionEachInterval(vibration)
            self.restore()
        })
        timer.fire()
    }

    private func accelerometerUpdatesHandler(data: CMAccelerometerData?, error: Error?) {
        guard error == nil else { debugPrint(error?.localizedDescription ?? ""); return }

        guard let data = data
            else { EHLogger.error(in: self, msg: "no error, no data"); return }

        let x = data.acceleration.x
        let y = data.acceleration.y

        // 初始化baseX，baseY
        if self.baseX == 0.0000 {
            self.baseX = x
        }

        if self.baseY == 0.0000 {
            self.baseY = y
        }

        // 比较baseX，baseY和x，y，计算出临时差值
        let tempOffsetX = x - self.baseX
        let tempOffsetY = y - self.baseY

        // 临时差值和缓存差值比较，把较大值保存在缓存差值中
        self.offsetX = max(tempOffsetX, self.offsetX)
        self.offsetY = max(tempOffsetY, self.offsetY)

        EHLogger.debug(in: self, msg: "1second:", self.offsetX, self.offsetY)
    }

    private func setUpMotionManager() {
        motionManager = CMMotionManager()
        motionManager.accelerometerUpdateInterval = 1
        motionManager.startAccelerometerUpdates(to: queue, withHandler: accelerometerUpdatesHandler)
    }
}
